<?php
namespace Cck\ArticlesSystem\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Cck\ArticlesSystem\Http\Models\Tag;
use Cck\ArticlesSystem\Http\Resources\TagResource;
use Cck\ArticlesSystem\Http\Requests\TagStoreRequest;
use Cck\ArticlesSystem\Http\Requests\TagUpdateRequest;
use Cck\ArticlesSystem\Http\Models\Taggable;

class TagsController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = (int)max($request->query('page_size', 15), 10);
        $page = (int)max($request->query('page', 1), 1);

        $tags = Tag::query()
            ->when($request->has('recommend'), function ($q) use ($request) {
                $q->where('recommend', (boolean)$request->query('recommend', true));
            })
            ->when($request->get('keyword'), function ($q, $keyword) {
                $q->where('name', 'like', '%' . $keyword . '%');
            })->paginate($pageSize, ['*'], 'page', $page);

        return TagResource::collection($tags);
    }

    public function all()
    {
        return TagResource::collection(Tag::all());
    }

    public function store(TagStoreRequest $request)
    {
        return new TagResource(
            Tag::query()->create($request->validated())
        );
    }

    public function update(Tag $tag, TagUpdateRequest $request)
    {
        $tag->update($request->validated());

        return ['status' => true];
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (!is_array($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        $ids = array_filter(array_unique(array_map('intval', $ids)));

        if (!count($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        DB::beginTransaction();

        $count = Tag::query()->whereIn('id', $ids)->delete();

        Taggable::query()->whereIn('tag_id', $ids)->delete();

        if (count($ids) !== $count) {
            DB::rollBack();

            return ['status' => false, 'message' => '删除失败'];
        }

        DB::commit();

        return ['status' => true];
    }
}
